﻿/*
 * File: TeamSelectionScene.cs
 * Author: Gourav Das
 * Purpose: Scene for Team Selection for One-off matches
 * Created: May 02 2011
 */

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Threading;
using System.Xml;
using _22yards._2D;
using _22yards.Scenes.Helpers;
using _22yards.Core;
using _22yards;

namespace _22yards.Scenes
{
    /// <summary>
    /// This is a scene that implements the 2D Gameplay screen
    /// </summary>
    class TeamSelectionScene : BaseMenuScene
    {
        List<Team> TeamsList = new List<Team>();
        ContentManager content;
        float pauseAlpha;

        //bool Team1Selected = false;
        //bool Team2Selected = false;

        private Texture2D _texSliderButton;
        private MenuButton _scrollUp;
        private MenuButton _scrollDown;
        /// <summary>
        /// Constructor.
        /// </summary>
        public TeamSelectionScene(string title):base(title)
        {

            // Create our menu entries.
            MenuItem ProceedMenuItem = new MenuItem("Proceed", 0, false, true);
            MenuItem BackMenuItem = new MenuItem("Back", 1, true);

            // Hook up menu event handlers.
            ProceedMenuItem.Selected += ProceedMenuItem_Selected;
            BackMenuItem.Selected += BackMenuItem_Selected;

            // Add Items to the menu.
            MenuItems.Add(ProceedMenuItem);
            MenuItems.Add(BackMenuItem);

            TransitioningTime = TimeSpan.FromSeconds(0.5);
            TransitionedTime = TimeSpan.FromSeconds(0.5);


        }

        /// <summary>
        /// Event handler for when the ProceedMenuItem_Selected is selected.
        /// </summary>
        void ProceedMenuItem_Selected(object sender, PlayerIndexEventArgs e)
        {
            ExitScene();
            TeamsList[0].IsUserSelected = true;
            TeamsList[1].IsUserSelected = false;
            sceneEngine.AddScene(new MatchSettingsScene("Match Settings",TeamsList[0],TeamsList[1]), ControllingPlayer);
            //LoadingScene.Load(sceneEngine, true, ControllingPlayer, new MatchSettings("Match Settings"));
        }


        /// <summary>
        /// Event handler for when the Back Menu is selected.
        /// </summary>
        void BackMenuItem_Selected(object sender, PlayerIndexEventArgs e)
        {
            ExitScene();
            string Title = string.Empty;
            switch (Game22Yards.match.TypeOfMatch / 10)
            {
                case 3:
                    if (Game22Yards.match.TypeOfMatch % 10 == 0 || Game22Yards.match.TypeOfMatch % 10 == 1)
                        Title = "Street Cricket";
                    else
                        Title = "Park Cricket";
                    break;

                case 2:
                    Title = "Domestic Cricket";
                    break;
                case 1:
                    Title = "International Cricket";
                    break;
            }

            sceneEngine.AddScene(new BottomBattlegroundMenuScene(Title), ControllingPlayer);
        }

        /// <summary>
        /// Load graphics and non graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(sceneEngine.Game.Services, "22yardsContent");

            _texSliderButton = content.Load<Texture2D>("TwoDEE/Screens/arrow");
            float scrollBarPos =sceneEngine.GraphicsDevice.Viewport.Width / 2f;
            scrollBarPos -= _texSliderButton.Width + ((float)2 * Game22Yards.scaleFactor.widthScale);

            _scrollUp = new MenuButton(_texSliderButton, false,
                                       new Vector2(scrollBarPos, ((float)200 * Game22Yards.scaleFactor.htScale) - _texSliderButton.Height), sceneEngine);
            _scrollDown = new MenuButton(_texSliderButton, true,
                                         new Vector2(scrollBarPos, ((float)400 * Game22Yards.scaleFactor.htScale) + _texSliderButton.Height), sceneEngine);
            //Load Teams according to type of match - Park, street, Domestic, International

            int typeID = Game22Yards.match.TypeOfMatch;
            foreach (int ID in Team.GetTeamIDsBasedOnType(typeID))
            {
                Team tm = new Team();
                if (!tm.initTeam())
                {
                    tm = null;
                    this.ExitScene();
                }
                tm.LoadTeamFromXML(ID);
                TeamsList.Add(tm);
            }

            // If loading is slow, uncomment below line and use LoadingScene in previous screen to load this screen
            sceneEngine.Game.ResetElapsedTime();

        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }

        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you switch to a different application.
        /// </summary>
        public override void Update(GameTime _gameTime, bool _otherSceneHasFocus,
                                                       bool _coveredByOtherScene)
        {
            base.Update(_gameTime, _otherSceneHasFocus, false);

            // Gradually fade in or out depending on whether we are covered by the pause screen.
            if (_coveredByOtherScene)
                pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1);
            else
                pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0);

            if (IsActive)
            {
                //base.Update(_gameTime, _otherScreenHasFocus, _coveredByOtherScreen);

                // Update each nested MenuEntry object.
                for (int i = 0; i < MenuItems.Count; i++)
                {
                    bool isSelected = IsActive && (i == SelectedItem);

                    MenuItems[i].Update(this, isSelected, _gameTime);
                }

            }
            //_scrollUp.Update(_gameTime);
            //_scrollDown.Update(_gameTime);
        }


        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        public override void HandleInput(InputEngine _input)
        {
            // Accept or cancel the menu? We pass in our ControllingPlayer,
            PlayerIndex playerIndex;

            int hoverIndex = GetMenuEntryAt(new Vector2(_input.LastMouseStates.X, _input.LastMouseStates.Y));
            if (hoverIndex > -1 && _input.MousePositionChanged(ControllingPlayer, out playerIndex))// IsMouseLeftButtonPress(ControllingPlayer,out playerIndex))
            {
                SelectedItem = hoverIndex;
            }
            else if (hoverIndex < 0 && _input.MousePositionChanged(ControllingPlayer, out playerIndex))// IsMouseLeftButtonPress(ControllingPlayer,out playerIndex))
            {
                SelectedItem = -1;
            }
            else //if (!_input.MousePositionChanged(ControllingPlayer, out playerIndex) && hoverIndex <0)
            {
                // Move to the previous menu item
                if (_input.IsMenuUp(ControllingPlayer) && !_input.MousePositionChanged(ControllingPlayer, out playerIndex))
                {
                    SelectedItem--;

                    //Cycle through Menu Items
                    if (SelectedItem < 0)
                        SelectedItem = MenuItems.Count - 1;
                }

                // Move to the next menu item
                if (_input.IsMenuDown(ControllingPlayer) && !_input.MousePositionChanged(ControllingPlayer, out playerIndex))
                {
                    SelectedItem++;

                    //Cycle through Menu Items
                    if (SelectedItem >=  MenuItems.Count)
                        SelectedItem = 0;
                }

                if (_input.IsMenuSelect(ControllingPlayer, out playerIndex) && !_input.MousePositionChanged(ControllingPlayer, out playerIndex))
                {
                    OnSelectEntry(SelectedItem, playerIndex);
                }
                else if (_input.IsMenuCancel(ControllingPlayer, out playerIndex) && !_input.MousePositionChanged(ControllingPlayer, out playerIndex))
                {
                    OnCancel(playerIndex);
                }
            }

            // Look up inputs for the active player profile.
            int playerIndex1 = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = _input.CurrentKeyboardStates[playerIndex1];
            GamePadState gamePadState = _input.CurrentGamePadStates[playerIndex1];

            // The game pauses either if the user presses the pause button, or if
            // they unplug the active gamepad. This requires us to keep track of
            // whether a gamepad was ever plugged in, because we don't want to pause
            // on PC if they are playing with a keyboard and have no gamepad at all!
            bool gamePadDisconnected = !gamePadState.IsConnected &&
                                       _input.GamePadWasConnected[playerIndex1];

            _scrollUp.Collide(new Vector2(_input.CurrentMouseStates.X, _input.CurrentMouseStates.Y));
            _scrollDown.Collide(new Vector2(_input.CurrentMouseStates.X, _input.CurrentMouseStates.Y));

        }

        /// <summary>
        /// Draws the Scene with the menus.
        /// </summary>
        public override void Draw(GameTime _gameTime)
        {
            UpdateMenuItemLocations();

            sceneEngine.SpriteBatch.Begin();

            // Draw each menu entry in turn.
            for (int i = 0; i < MenuItems.Count; i++)
            {
                MenuItem menuItem = MenuItems[i];

                bool isSelected = IsActive && (i == SelectedItem);

                menuItem.Draw(this, isSelected, _gameTime);
            }

            // Make the menu title slide into place during transitions, this makes
            // the movement slow down as it nears the end
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // Draw the menu title centered on the screen
            Vector2 titlePosition = new Vector2(sceneEngine.GraphicsDevice.Viewport.Width / 2, ((float)80 * Game22Yards.scaleFactor.htScale));
            Vector2 titleOrigin = sceneEngine.TxtNFont.spFontGoodTimes.MeasureString(MenuTitle) / 2;

            Vector2 leftpos = new Vector2(((float)350 * Game22Yards.scaleFactor.widthScale), ((float)250 * Game22Yards.scaleFactor.htScale));
            Vector2 rightpos = new Vector2(((float)800 * Game22Yards.scaleFactor.widthScale), ((float)250 * Game22Yards.scaleFactor.htScale));

            titlePosition.Y -= transitionOffset * 100;
            //leftpos.Y -= transitionOffset * 500;
            //rightpos.Y -= transitionOffset * 500;
            leftpos.X -= transitionOffset * 500;
            rightpos.X += transitionOffset * 500;
            //Draw main menu title
            sceneEngine.SpriteBatch.DrawString(sceneEngine.TxtNFont.spFontGoodTimes, MenuTitle, titlePosition, Color.White, 0,
                                   titleOrigin, 1.5f, SpriteEffects.None, 0);


            foreach (Team t1 in TeamsList)
            {
                sceneEngine.SpriteBatch.DrawString(sceneEngine.TxtNFont.spFontPescadero, t1.TeamName, leftpos, Color.White);
                sceneEngine.SpriteBatch.DrawString(sceneEngine.TxtNFont.spFontPescadero, t1.TeamName, rightpos, Color.White);
                leftpos.Y += ((float)25 * Game22Yards.scaleFactor.htScale);
                rightpos.Y += ((float)25 * Game22Yards.scaleFactor.htScale);
            }
            //_scrollUp.Draw();
            //_scrollDown.Draw();
            sceneEngine.SpriteBatch.End();
        }


        /// <summary>
        /// When the user presses ESC, do nothing.
        /// </summary>
        protected override void OnCancel(PlayerIndex _playerIndex)
        {
            //Do nothing :)
        }
    }

}
